import { defineStore } from 'pinia'
import { familyListQueryData,family } from '@/api/family/type'
import { getFilterList } from '@/api/family'

export const useFamilyStore = defineStore('family', () => {
    const familyQueyryData = reactive<familyListQueryData>({
        name: '',
        gender: '',
        generation: ''
    })
    const familyTangList = ref<family[]>([])
    const getFilterListFunc = async () => {
        const res = await getFilterList(familyQueyryData)
        if (res.code === 200) {
            if (familyTangList.value.length != 0) { 
                familyTangList.value.length = 0
            } 
            familyTangList.value = buildFamilyTree(res.data)
            return Promise.resolve(res.msg)
        } else {
            return Promise.reject(res.msg)
        }
    }

    return {
        familyQueyryData,
        familyTangList,
        getFilterListFunc,
    }
})

function buildFamilyTree(data: family[]): family[] {
  const map: Record<number, family> = {};

  // 构建成员映射表
  data.forEach(member => {
    map[member.ID] = member;
  });

  // 遍历数据，建立父子和母子关系
  data.forEach(member => {
    if (member.father_id !== 0 && map[member.father_id]) {
      const father = map[member.father_id];
      if (!father.children) {
        father.children = [];
      }
      father.children.push(member);

      if (!father.parents) {
        father.parents = [];
      }
      father.parents.push(member);
    }

    if (member.mother_id !== 0 && map[member.mother_id]) {
      const mother = map[member.mother_id];
      if (!mother.children) {
        mother.children = [];
      }
      mother.children.push(member);

      if (!mother.parents) {
        mother.parents = [];
      }
      mother.parents.push(member);
    }
  });

  // 找到根节点（父亲ID和母亲ID都为0的成员）
  return data.filter(member => member.father_id === 0 && member.mother_id === 0);
}